#!/usr/bin/env python

import sys
from scapy.all import *
from subprocess import check_output, CalledProcessError

TIMEOUT = 3 # en seg.

def ping(host, debug = False):
  packet = IP(dst=host)/ICMP()
  verb = 0 if debug == False else None
  response = sr1(packet, verbose = verb, timeout = TIMEOUT)
  return response

#devuelve una lista de ips por los que pasas los paquetes
def traceroute(host, maxttl = 30, debug = False):
	route = []
	p = IP(dst = host, ttl = 1, id = 1) / ICMP()
	ip = p.src
	lastip = ip
	
	for t in range(1,maxttl):
		p.ttl = t
		p.id = t
		
		verb = 0 if debug == False else None
		resp = sr1(p, timeout = TIMEOUT, verbose = verb)

		if resp == None:
			route.append("***")
		else:
			if resp.src == ip or resp.src == lastip:
				break

			route.append(resp.src)			
			lastip = resp.src

	return route

"""
si logra pinguear devuelve
  'rtt min/avg/max/mdev = 178.343/197.866/226.556/17.343 ms\n'
sino vacio
"""
def linux_ping(host, reps):
  try:
    ping = check_output("ping " + host + " -c " + str(reps) + " -W " + str(TIMEOUT) + " | grep rtt", shell=True)
    stats = ping.split()
    stats = stats[3]
    stats = stats.split('/')
    return stats[1]
  except CalledProcessError:
    return '1000'
